<?php


namespace app\admin\controller;

use app\common\model\mysql\AdminUser;
use think\facade\View;
use app\admin\validate\AdminUser as Validate;

class Login extends AdminBase
{
    public function initialize()
    {
//        dump(session(config('admin.session_admin')));
        if ($this->isLogin()) {
            return $this->redirect(url('index/index'));
        }
    }


    //显示登陆页面
    public function index()
    {
        return View::fetch();
    }

    //前端验证码校验
    public function check()
    {
        //判断是不是post请求
        if (!$this->request->isPost()) {
            return show(config('status.error'), '请求方式错误!');
        }

        //参数校验 1.原生方式 2.tp6验证机制
        $username = $this->request->param('username', '', 'trim');
        $password = $this->request->param('password', '', 'trim');
        $captcha = $this->request->param('captcha', '', 'trim');

//        if (empty($captcha) || empty($username) || empty($password)) {
//            return show(config('status.error'), '参数不能为空!');
//        }
        $data = [
            'username' => $username,
            'password' => $password,
            'captcha' => $captcha,
        ];
        $validate = new Validate();
        if (!$validate->check($data)) {
            return show(config('status.error'), $validate->getError());
        }

        //验证码校验,需要在模块中间件开启session
//        if (!captcha_check($captcha)) {
//            //验证码校验失败
//            return show(config('status.error'), '验证码错误!');
//        }
        try {
            $result = \app\admin\business\AdminUser::login($data);

        } catch (\Exception $e) {
            return show(config('status.error'), $e->getMessage());
        }
        if ($result) {
            return show(config('status.success'), '登录成功!');
        } else {
            return show(config('status.error'), '登录失败!');
        }

    }
}
